package link.hwx.controller.u9;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import link.hwx.entity.oa.OaUserInfo;
import link.hwx.service.oa.OaInfoService;
import link.hwx.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * srm请购单接口
 */
@RestController
@RequestMapping("/cx/srm")
public class SrmPrOpenApi {

    @Autowired
    private OaInfoService oaInfoMapper;

    @PostMapping("/screatePr")
    public AjaxResult sCreatePo(@RequestBody Map<String, Object> jsonStr) {
        if (jsonStr == null) {
            Map<String, Object> result = new HashMap<String, Object>();
            return AjaxResult.error("数据不能为空!");
        }
        Map<String, Object> currentUser = (Map<String, Object>) jsonStr.get("currentUser");
        //String apprName = (String) currentUser.get("loginid");//当前操作人名 用作审核人
        String result = createPr(jsonStr);
//        System.out.println("请购单："+jsonStr);
        if (StringUtils.isNotEmpty(result)) {
            JSONObject resultmap = JSON.parseObject(result);
            if (resultmap.getBoolean("Success")) {
                String mCode = resultmap.getString("VoucherCode");
                String requestId = jsonStr.get("requestId") + "";
                //修改oa表单标题
                //oaInfoService.updateWorkflowTableTitle(" srm" + mCode, "73098", "6");
                oaInfoMapper.updateMemoByRequestId(CommonSetData.oaPrTableMainDbNameD, " srm" + mCode, requestId);
                return AjaxResult.success();


            } else {
                return AjaxResult.error(resultmap.getString("Message"));
            }
        }
        return AjaxResult.error();
    }

    public static void main(String[] strs) {
        //String msId = "1002206230162119";
        String s = "base64:123";
        System.out.println(StringUtils.isBlank(s) ? s : s.substring(7, s.length()));

    }

    public String createPr(Map<String, Object> oaMapData) {
        String srmUrl = CommonSetData.serveSrmIp + CommonSetData.srmPrUrlCreat;
        String userpwd = StringUtil.md5(CommonSetData.srmUserPwd);
        JSONObject user = new JSONObject();
        user.put("usercode", CommonSetData.srmUserCode);
        user.put("userpwd", userpwd);
        JSONObject voucher = new JSONObject();
        voucher.put("voucherno", CommonSetData.voucherno);
        voucher.put("formid", CommonSetData.formid);
        JSONObject head = new JSONObject();
        head.put("ccode", oaMapData.get("djbh"));
        head.put("ccommit", oaMapData.get("zdr"));
        head.put("cmaker", oaMapData.get("zdrm"));
        head.put("cmakercode", oaMapData.get("zdrid"));
        head.put("cremark", oaMapData.get("bz"));
        head.put("csourcecode", oaMapData.get("djbh"));
        head.put("csourceid", oaMapData.get("lcid"));
        head.put("cstate", "通过");
        head.put("curgency", oaMapData.get("jjcd"));
        head.put("ddate", oaMapData.get("djrq"));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        head.put("dverydate", sdf.format(new Date()));
        head.put("ccglxcode", oaMapData.get("cglxbh"));
        head.put("ccglxid", oaMapData.get("cglxid"));
        head.put("ccglxname", oaMapData.get("cglxmc"));
        head.put("ccorpcode", oaMapData.get("zzbh"));
        head.put("corg_id", oaMapData.get("zzid"));
        head.put("ccorpname", oaMapData.get("zzmc"));
        head.put("cdep_id", oaMapData.get("bmid"));
        head.put("cdepcode", oaMapData.get("bmbh"));
        head.put("cdepname", oaMapData.get("bmmc"));
        head.put("bemergency", oaMapData.get("sfjx"));
        JSONObject armbody = new JSONObject();
        JSONArray focus_srm_purchaseapplyline = new JSONArray();
        List<List<Map<String, Object>>> detailList = (List<List<Map<String, Object>>>) oaMapData.get("detailData");
        for (int i = 0; i < detailList.size(); i++) {
            for (int j = 0; j < detailList.get(i).size(); j++) {
                Map<String, Object> detal = detailList.get(i).get(j);//列数据;
                JSONObject srmLine = new JSONObject();
                srmLine.put("citem_id", detal.get("lpid"));
                srmLine.put("iquan", detal.get("pzsl"));
                srmLine.put("cu8item_code", detal.get("u8wlbm"));
                srmLine.put("citemdescription", detal.get("wlms"));
                srmLine.put("clineremark", detal.get("bz"));
                srmLine.put("cdemandpeopleid", detal.get("xqrid"));
                srmLine.put("cdemandpeople", detal.get("xqr"));
                srmLine.put("cteleplone", detal.get("xqrlxdh"));
                srmLine.put("cdeliveryaddress_id", detal.get("jhdzid"));
                srmLine.put("cdeliveryaddress", detal.get("jhdz"));
                String wlms1 = (String) detal.get("wlms1");
                String jzms = (String) detal.get("jzms");
                String ppyq = (String) detal.get("ppyq");
                String brand ="物料描述:"+wlms1+"/"+"介质描述:"+jzms+"/"+"品牌要求:"+ppyq;
                srmLine.put("cbrand",brand);
                if (detal.get("scfj")!=null&&detal.get("scfj")!=""){
                    String sjarry[] = detal.get("scfj").toString().split(",");
                    OaUserInfo filemap = oaInfoMapper.findFileInfoByDocID(String.valueOf(sjarry[0]));
                String filename = filemap.getImagefilename();
                String filepath = filemap.getFilerealpath();
                if (StringUtils.isNotBlank(filepath)) {
                    String zipFilePath = filepath;
                    String destDirectory = CommonSetData.oaZCFilePath;
                    String fileName = UnzipUtil.unzip(zipFilePath, destDirectory);
                    String base64str = "";
                    try {
                        String filetype = ".pdf";
                       /* if (StringUtils.isNotBlank(filename)) {
                            filetype = filename.substring(filename.lastIndexOf("."));
                        }*/
                       // String strname = zipFilePath.substring(zipFilePath.lastIndexOf("\\") + 1, zipFilePath.lastIndexOf("."));
                        String newFileUrl = destDirectory + File.separator + fileName;
                        File file = new File(newFileUrl);
                        base64str = Base64Util.fileToBase64Str(file);
                        file.delete();//删除文件
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Map<String, String> fileInfo = new HashMap<String, String>();
                    fileInfo.put("filename", filename);
                    fileInfo.put("buffer", base64str);

                    srmLine.put("caccessory", fileInfo);
                } else {
                    srmLine.put("caccessory", "");
                }}
                srmLine.put("ddeliverydate", detal.get("jydhrq"));
                focus_srm_purchaseapplyline.add(srmLine);
            }
        }
        armbody.put("focus_srm_purchaseapplyline", focus_srm_purchaseapplyline);
        JSONObject datatable = new JSONObject();
        datatable.put("user", user);
        datatable.put("voucher", voucher);
        datatable.put("head", head);
        datatable.put("body", armbody);
        String data = JSON.toJSONString(datatable);
        JSONObject copy = JSON.parseObject(data);
        // 使用 Stream 处理数组
        copy.getJSONObject("body")
                .getJSONArray("focus_srm_purchaseapplyline")
                .forEach(item -> ((JSONObject)item).remove("caccessory"));
        String data1 = JSON.toJSONString(copy);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
        builder.addTextBody("data", data, contentType);
        String s1 = HttpManager.sendPostFormData(srmUrl, builder,data1);
        // System.out.println("qingoudan11111:"+builder);
        //String s1 = doPostformdata(srmUrl, data);
        return s1;

    }


}
